package main

import (
	"embed"
	"encoding/json"
	"fmt"
	"github.com/goburrow/modbus"
	"github.com/robfig/cron/v3"
	"log"
	"net/http"
	"os"
	"strconv"
	"time"
	"water-temperature-server/config"
	"water-temperature-server/daos"
	"water-temperature-server/jobs"
	"water-temperature-server/models"
	"water-temperature-server/service"
)

//go:embed config
var AssertFile embed.FS

// IsSend 为false 接收数据；true 发送数据
var IsSend = true

func main() {
	Start()
	if IsSend == true {
		clientHandler := modbus.NewTCPClientHandler("127.0.0.1:503")
		clientHandler.SlaveId = 2
		errConnect := clientHandler.Connect()
		if errConnect != nil {
			log.Fatal("Error connecting to Modbus server:", errConnect)
		}
		defer clientHandler.Close()
		c := cron.New(cron.WithSeconds(), cron.WithChain(cron.SkipIfStillRunning(cron.VerbosePrintfLogger(log.New(os.Stdout, "cron: ", log.LstdFlags)))))
		spec1 := "1 * * * * ?" //cron表达式，每5分钟一次 泵站
		c.AddFunc(spec1, func() {
			timeM, _ := strconv.Atoi(time.Now().Format("04"))
			if timeM%2 == 0 { // 每2分钟取一条数据
				go jobs.StartSyncData(clientHandler)
			}
		})
		c.Start()
		http.HandleFunc("/pong", myHandler)
	} else {
		http.HandleFunc("/data", dataHandler)
	}
	http.ListenAndServe("0.0.0.0:8082", nil)
}

func myHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("success"))
}
func dataHandler(w http.ResponseWriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)
	var params []models.WaterTemperaTure
	err := decoder.Decode(&params)
	if err != nil {
		fmt.Printf("数据错误:%v\n", err.Error())
		w.Write([]byte(fmt.Sprintf("数据错误:%v", err.Error())))
	} else {
		temperatureService := service.TemperatureService{}
		temperatureService.InsetBatch(&params)
		w.Write([]byte("success"))
	}
}

func tips() {
	fmt.Println("========================================")
	fmt.Println()
	str := "同步"
	if !IsSend {
		str = "接收"
	}
	fmt.Printf("马岭水库水温%v数据程序启动成功！\n\n技术支撑QQ:397633183 \n\n请勿关闭程序!%s\n", str, time.Now().Format("2006-01-02 15:04:05"))
	fmt.Println()
	fmt.Println("========================================")
}

func Start() {
	tips()
	config.OpenDB(AssertFile)
	if IsSend == false {
		daos.OpenConnect()
	}
}
